package com.atguigu.gmall.auth.service;

import com.atguigu.gmall.common.utils.IpUtils;
import com.atguigu.gmall.ums.entity.UserEntity;
import com.atguigu.gmall.auth.config.JwtProperties;
import com.atguigu.gmall.auth.feign.UmsFeignClient;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.common.utils.CookieUtils;
import com.atguigu.gmall.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Service
@EnableConfigurationProperties(JwtProperties.class)
public class AuthService {

    @Autowired
    UmsFeignClient umsFeignClient;

    @Autowired
    JwtProperties jwtProperties;

    public void login(String url, String username, String password, HttpServletRequest request, HttpServletResponse response) {
        // 1.检查用户登录信息是否正确
        UserEntity userEntity;
        try {
            ResponseVo<UserEntity> userEntityResponseVo = umsFeignClient.queryUser(username, password);
            userEntity = userEntityResponseVo.getData();
        } catch (Exception e) {
            throw new RuntimeException("用户名或密码错误");
        }
        // 2.生成jwt令牌
        // 2.1获取公钥 签名
        // 2.2创建载荷
        Map<String,Object> map = new HashMap<>();
        map.put("username",userEntity.getUsername());
        map.put("userId",userEntity.getId());
        map.put("ip", IpUtils.getIpAddressAtService(request));
        // 2.3生成令牌 设置过期时间
        try {
            String token = JwtUtils.generateToken(map, jwtProperties.getPrivateKey(), jwtProperties.getExpire() * 60);
            //把token放入cookie中
            CookieUtils.setCookie(request,response,jwtProperties.getCookieName(),token,jwtProperties.getExpire()*60);
            //把用户昵称放入cookie中
            CookieUtils.setCookie(request,response,jwtProperties.getUnick(),userEntity.getNickname(),jwtProperties.getExpire()*60);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
